package com.mytinyRPC.protocol.http;

import com.alibaba.fastjson.JSONObject;
import com.mytinyRPC.framework.Invocation;
import com.mytinyRPC.protocol.RpcClient;
import com.mytinyRPC.serializer.CommonSerializer;

import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClient implements RpcClient {

    private final CommonSerializer serializer=CommonSerializer.getByCode(1);

    public String send(String hostname, Integer port, Invocation invocation){

        //HttpClient封装http请求发送给服务器
        String result=new String();
        try{
            HttpRequest request=HttpRequest.newBuilder()
                    .uri(new URI("http",null,hostname,port,"/",null,null))
                    .POST(HttpRequest.BodyPublishers.ofByteArray(serializer.serialize(invocation)))
                    .build();
             java.net.http.HttpClient client= java.net.http.HttpClient.newHttpClient();

            HttpResponse<String> response=client.send(request,HttpResponse.BodyHandlers.ofString());
            result=response.body();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return result;


    }

}
